import asyncio
import websockets
import time
import requests
import json
import random


headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36'
}

topics = [
    'CONFIG_10_0',
    'OVInPlay_10_0',
    'Media_L10_Z0',
    'XL_L10_Z0_C1_W3'
]

open_topics = {
    'en': 'CONFIG_1_3,OVInPlay_1_3,Media_L1_Z3,XL_L1_Z3_C1_W3', # 英文
    'zh': 'CONFIG_10_10,OVInPlay_10_10,Media_L10_Z10,XL_L10_Z10_C10_W10', # 中文
    'cht': 'CONFIG_2_0,OVInPlay_2_0,Media_L2_Z0,XL_L2_Z0_C2_W3', # 繁體
}

def get_uid():
    return f'{random.random()}'[2:]

def fetch_session_id():
    url = 'https://www.348365365.com/'

    s = requests.Session()
    s.headers.update(headers)
   
    try:
        resp = s.get(url) # request 1
        print(resp.cookies['pstk'])
        time.sleep(1)
        resp = s.get(url) # request 2
        print(resp.cookies['pstk'])
        session_id = resp.cookies['pstk']
        return session_id
    except:
        return ''


def parse_recv(msg):
    return json.loads(msg)


async def start(session_id):
    url = f'wss://pshudws.365pushodds.com/zap/?uid={get_uid()}'
    file = 'bet3652.txt'

    with open(file, 'w') as f:
        f.write('w'*1000 + '\n')

    async with websockets.connect(url, extra_headers=headers, subprotocols=['zap-protocol-v1']) as ws:
        msg = f'#P__time,S_{session_id}\x00'
        print(msg)
        await ws.send(msg)
        while True:
            greeting = await ws.recv()
            print(f"↓ {greeting}")

            if session_id in greeting:
                msg = f'\x00commandgetMessage{session_id}SPTBK10'
                await ws.send(msg)

            with open(file, 'a') as f:
                msg = f'[{time.strftime("%Y-%m-%d %H:%M:%S")}]{greeting}\n\n'

                f.write(msg)
            

async def start2(session_id):
    url = f'wss://premws-pt1.365lpodds.com/zap/?uid={get_uid()}'
    file = 'bet365.txt'

    with open(file, 'w') as f:
        f.write('w'*1000 + '\n')

        
    # headers.update({
    #     'Accept-Encoding':'gzip, deflate, br',
    #     'Accept-Language':'zh-CN,zh;q=0.9',
    #     'Cache-Control':'no-cache',
    #     'Host':'premws-pt2.365pushodds.com',
    #     'Pragma':'no-cache',
    #     'Origin':'https://www.348365365.com'})

    async with websockets.connect(url, extra_headers=headers, subprotocols=['zap-protocol-v1']) as ws:
        msg = f'#P__time,S_{session_id}\x00'
        await ws.send(msg)
        
        while True:
            greeting = await ws.recv()
            print(f"↓ {greeting}")

            if greeting[0] == '1':
                # for topic in topics:
                #     msg = f'\x00{topic}'
                # msg = f'\x00{open_topics["en"]}'
                msg = f'\x00Media_L1_Z3'
                
                # await asyncio.sleep(0.3)
                await ws.send(msg)
            if greeting[1:7] == '__time':
                # msg = f'\x00{topic}'
                msg = f'\x00Media_L1_Z3'
                # msg = f'\x006V77019265C18A_2_0'
                
                # await asyncio.sleep(0.3)
                await ws.send(msg)

            with open(file, 'a') as f:
                f.write(f'[{time.strftime("%Y-%m-%d %H:%M:%S")}] {greeting[:]} \n')
            



if __name__ == '__main__':
    
    session_id = fetch_session_id()
    # session_id = '32D2B95383E74F96A3D93E6B69D10796000003'
    # print(session_id)
    if session_id:
        asyncio.get_event_loop().run_until_complete(start2(session_id))
        # asyncio.get_event_loop().run_until_complete(start(session_id))
